<template>
  <div class="header">
    <el-button type="primary" @click="addManagerInfoBtn">
      添加管理员 <el-icon class="el-icon--right"><Plus /></el-icon>
    </el-button>
  </div>
  <el-table
    :header-cell-style="headerRowStyle"
    :data="computedTableDate"
    :cell-style="{ textAlign: 'center' }"
    style="width: 80%; margin: 0 auto"
  >
    <el-table-column type="index" label="Date" width="80" />
    <el-table-column prop="adminname" label="管理员ID" />
    <el-table-column label="权限">
      <template #default="scope">
        <el-tag :type="scope.row.role == 1 ? '' : 'success'">
          {{ scope.row.role == 1 ? '管理员' : '超级管理员' }}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column label="管理">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.row)">
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页器 -->
  <el-pagination
    background
    layout="prev, pager, next"
    :total="tableData.length"
    v-model:page-size="pageSize"
    v-model:current-page="currentPage"
  />
  <!-- 右侧的抽屉 -->
  <el-drawer v-model="showDrawer">
    <template #title>
      <h4>{{ currType == 1 ? '添加管理员' : '修改管理员数据' }}</h4>
    </template>
    <template #default>
      <el-form
        label-position="right"
        label-width="80px"
        :model="formData"
        style="max-width: 460px"
      >
        <el-form-item label="账户">
          <el-input v-model="formData.adminname" :disabled="currType == 2" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="formData.password" :disabled="currType == 2" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select
            v-model="formData.role"
            class="m-2"
            placeholder="请选择角色"
          >
            <el-option label="管理员" value="1" />
            <el-option label="超级管理员" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="权限：">
          <el-tree
            :data="menus"
            ref="treeRef"
            show-checkbox
            node-key="path"
            default-expand-all
            :default-checked-keys="defaultCheckedKeys"
          />
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="this.showDrawer = false">退出</el-button>
        <el-button
          type="primary"
          v-if="currType == 2"
          @click="domupdateManager"
        >
          修改
        </el-button>
        <el-button type="primary" v-else @click="confirmClick">添加</el-button>
      </div>
    </template>
  </el-drawer>
</template>
<script>
import _ from 'lodash'
import { Plus } from '@element-plus/icons-vue'
import {
  updataManager,
  deleteManager,
  addManager,
  updateManager
} from '@/api/user.js'
import { routes } from '@/router'
import { mapState, mapMutations } from 'vuex'
export default {
  created() {
    const cloneRoutes = _.cloneDeep(routes[1].children)
    cloneRoutes[1].children.pop()
    this.menus = cloneRoutes
    this.getTabList()
  },
  components: {
    Plus
  },
  data() {
    return {
      currType: 1,
      defaultCheckedKeys: [],
      showDrawer: false,
      pageSize: 10,
      currentPage: 1,
      headerRowStyle: {
        color: 'rgba(0,0,0,0.85)',
        fontWeight: '700',
        fontSize: '14px',
        textAlign: 'center',
        background: '#f8f8f8',
        height: '60px',
        borderRight: '1px solid #f0f0f0',
        transition: 'background .3s ease'
      },
      tableData: [],
      formData: {
        adminname: '',
        password: '',
        role: '1',
        checkedKeys: []
      },
      menus: routes[1].children
    }
  },
  computed: {
    ...mapState(['userInfo']),
    computedTableDate() {
      return this.tableData.slice(
        (this.currentPage - 1) * this.pageSize,
        (this.currentPage - 1) * this.pageSize + this.pageSize
      )
    }
  },
  methods: {
    ...mapMutations(['upfdataUserInfo']),
    addManagerInfoBtn() {
      this.currType = 1
      this.showDrawer = true
      this.formData.adminname = ''
      this.formData.password = ''
      this.formData.role = '1'
      this.formData.checkedKeys = []
      if (this.$refs.treeRef) {
        // 后续再次点击编辑的时候，重置成为之前的样子

        this.$refs.treeRef.setCheckedKeys([])
      }
    },
    updataManagerBtn() {
      let list = this.$refs.treeRef.getCheckedNodes(true)
      const tempList = []
      const result = []
      list.forEach((item) => {
        const parent = this.menus.find((mitem) => {
          return mitem.children.some((child) => child.label === item.label)
        })
        console.log('---parent-', parent)
        if (!tempList.includes(parent.label)) {
          tempList.push(parent.label)
          result.push({
            label: parent.label,
            path: parent.path,
            children: [item]
          })
        } else {
          // console.log('---result', result)
          // result.find(item=>{
          //   console.log(item.label,parent.label,item.label===parent.label)
          // })
          result.find((item) => item.label === parent.label).children.push(item)
        }
      })
      // console.log(list, result)
      this.formData.checkedKeys = result
    },
    //修改管理员数据
    domupdateManager() {
      this.updataManagerBtn()
      updateManager(this.formData).then(() => {
        //如果修改自己的账户 左边菜单栏 自动修改
        if (this.userInfo.adminname == this.formData.adminname) {
          // console.log('123--------->')
          this.userInfo.checkedkeys = this.formData.checkedKeys
          this.upfdataUserInfo(this.userInfo)
        }
        this.showDrawer = false
        this.getTabList()
      })
    },

    //添加管理员
    confirmClick() {
      this.currType = 1
      // console.log(this.currType)
      this.updataManagerBtn()
      addManager(this.formData).then(() => {
        this.showDrawer = false
        this.getTabList()
      })
    },
    //修改管理员
    handleEdit(row) {
      this.currType = 2
      this.showDrawer = true
      this.formData.adminname = row.adminname
      this.formData.password = row.password
      this.formData.role = row.role.toString()
      const checkedKeys = []
      row.checkedKeys.forEach((parent) => {
        parent.children.forEach((child) => {
          checkedKeys.push(child.path)
        })
      })
      this.defaultCheckedKeys = checkedKeys
      if (this.$refs.treeRef) {
        // 后续再次点击编辑的时候，重置成为之前的样子
        this.$refs.treeRef.setCheckedKeys(checkedKeys)
      }
    },
    //删除管理员
    handleDelete(row) {
      deleteManager({
        adminid: row.adminid
      }).then(() => {
        this.getTabList()
        this.currentPage = 1
      })
    },
    getTabList() {
      updataManager().then((res) => {
        this.tableData = res.data || []
      })
    }
  }
}
</script>
<style scoped lang="scss">
.el-pagination {
  position: relative;
  left: 66%;
}
.header {
  button {
    margin-bottom: 20px;
    margin-top: 15px;
  }
}
.manager-container {
  height: 100%;
  padding: 0 24px;
  background: #fff;
  .header {
    padding: 16px 0;
  }
}
</style>
